package com.tensquare.user.service;

import com.tensquare.user.dao.UserDao;
import com.tensquare.user.pojo.User;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import util.IdWorker;

import java.util.HashMap;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
public class UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder encoder;

    //1.发送手机验证码（code放入redis，再通过mq发送出去）
    public void sendSms(String mobile){
        //1.生成六位数的验证码
        //1.1定义最大值和最小值
        int min=100000;
        int max=999999;
        //1.2生成一个随机对象
        Random random = new Random();
        //1.3生成一个随机数字0-89999之间
        int rand=random.nextInt(max-min);
        //1.4确定验证码
        int code=rand+min;
        System.out.println("验证码----->"+code);
        //2.将验证码放入redis中
        redisTemplate.opsForValue().set(mobile,code+"",5,TimeUnit.MINUTES);
        //3.将消息发送给微服务监听方，然后监听方再发送给阿里大于
        //3.1封装数据
        HashMap map = new HashMap<>();
        map.put("mobile",mobile);
        map.put("code",code+"");
        //3.2发送出去
        rabbitTemplate.convertAndSend("sms",map);
    }
    //2.判断验证码是否正确
    public boolean isExistsCode(String code, String mobile) {
        //2.1根据手机号从redis中获取验证码
        String redisCode = (String) redisTemplate.opsForValue().get(mobile);
        //2.2判断验证码不为空
        if(StringUtils.isNotBlank(code) && StringUtils.isNotBlank(redisCode)){
            //2.2.1返回结果
            return redisCode.equals(code);
        }
        //2.3返回结果
        return false;
    }
    //3.添加用户
    public void add(User user) {
        //3.1设置用户id
        user.setId(idWorker.nextId()+"");
        //3.2对密码进行加密
        user.setPassword(encoder.encode(user.getPassword()));
        //3.3添加到数据库中
        userDao.save(user);
    }
    //4.判断用户是否登录
    public User login(User user) {
        //4.1根据手机号查询用户
        User findUser=userDao.findByMobile(user.getMobile());
        //4.2判断用户输入的密码是否正确
        if(findUser!=null && StringUtils.isNotBlank(user.getPassword()) &&
                encoder.matches(user.getPassword(),findUser.getPassword())){
            //4.2.1返回当前用户
            return findUser;
        }
        //4.3返回空
        return null;
    }
    //5.更新粉丝数
    public void incfans(String userId,int num){
        userDao.incfans(userId,num);
    }
    //6.更新关注数
    public void incfollow(String userId,int num){
        userDao.incfollow(userId,num);
    }

}
